﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.AccessControl;
using System.Management;
using System.Security.Principal;

namespace HandLab.LocalApp.AccessControl
{
    public class AcTest
    {
        public void AclTest()
        {
            /*
              */

            // GetUsers();

            //DirectoryInfo di1 = Directory.CreateDirectory(@"C:\Users\david.cao\Desktop\src\111");
            //DirectoryInfo di2 = Directory.CreateDirectory(@"C:\Users\david.cao\Desktop\src\222");
            //DirectoryInfo di3= Directory.CreateDirectory(@"C:\Users\david.cao\Desktop\src\333");
            //DirectoryInfo di4 = Directory.CreateDirectory(@"C:\Users\david.cao\Desktop\src\444");

            // retrieving the directory information
            DirectoryInfo myDirectoryInfo = new DirectoryInfo(@"C:\Users\david.cao\Desktop\src");

            // Get a DirectorySecurity object that represents the 
            // current security settings.
            DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
            string sAccessInfo = string.Empty;
            foreach (FileSystemAccessRule FSAR in myDirectorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
            {
                sAccessInfo += GetAceInformation(FSAR);
            }

            // Add the FileSystemAccessRule to the security settings. 
            // FileSystemRights is a big list we are current using Read property but you 
            // can alter any other or many sme of which are:
            // Create Directories: for sub directories Authority
            // Create Files: for files creation access in a particular folder
            // Delete: for deletion athority on folder
            // Delete Subdirectories and files: for authority of deletion over 
            //subdirectories and files
            // Execute file: For execution accessibility in folder
            // Modify: For folder modification
            // Read: For directory opening
            // Write: to add things in directory
            // Full Control: For administration rights etc etc

            // Also AccessControlType which are of two kinds either “Allow” or “Deny” 
            //myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User,
            //                             FileSystemRights.Read, AccessControlType.Deny));

            // Set the new access settings. 
            myDirectoryInfo.SetAccessControl(myDirectorySecurity);

            // Showing a Succesfully Done Message
            //MessageBox.Show("Permissions Altered Successfully");
        }

        public void GetUsers()
        {
            // This query will query for all user account names in our current Domain
            SelectQuery sQuery = new SelectQuery("Win32_UserAccount", "Domain='"
                          + System.Environment.UserDomainName.ToString() + "'");

            try
            {
                // Searching for available Users
                using (ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery))
                {
                    foreach (ManagementObject mObject in mSearcher.Get())
                    {
                        // Adding all user names in our combobox
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }
        }

        private void CheckSecurity(DirectoryInfo[] DIArray)
        {
            foreach (DirectoryInfo di in DIArray)
            {
                DirectorySecurity DirSec = di.GetAccessControl(AccessControlSections.All);
                string sAccessInfo = string.Empty;

                foreach (FileSystemAccessRule FSAR in DirSec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
                {
                    sAccessInfo += GetAceInformation(FSAR);
                }

                if (sAccessInfo != string.Empty)
                {
                    // Write info to text file
                }
            }
        }

        private string GetAceInformation(FileSystemAccessRule ace)
        {
            StringBuilder info = new StringBuilder();
            string line = string.Format("Account: {0}", ace.IdentityReference.Value);
            info.AppendLine(line);
            line = string.Format("Type: {0}", ace.AccessControlType);
            info.AppendLine(line);
            line = string.Format("Rights: {0}", ace.FileSystemRights);
            info.AppendLine(line);
            line = string.Format("Inherited ACE: {0}", ace.IsInherited);
            info.AppendLine(line);
            return info.ToString();
        }


        public static void AddUserToAcl(string filename)
        {
            // create a rule for self
            WindowsIdentity self = WindowsIdentity.GetCurrent();
            FileSystemAccessRule rule = new FileSystemAccessRule(
                self.Name, FileSystemRights.FullControl,
                AccessControlType.Allow);
            // add the rule to the file's existing ACL list
            FileSecurity security = File.GetAccessControl(filename);
            AuthorizationRuleCollection acl = security.GetAccessRules(true, true,
                typeof(System.Security.Principal.NTAccount));
            security.AddAccessRule(rule);
            // persist changes and update view
            File.SetAccessControl(filename, security);
        }
    }
}
